package com.stack.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stack.admin.mapper.AdUserMapper;
import com.stack.admin.service.AdUserService;
import com.stack.common.utils.jwt.AdminJwtUtil;
import com.stack.common.utils.thread.AdminThreadLocalUtil;
import com.stack.model.admin.dtos.AdUserDto;
import com.stack.model.admin.dtos.PageQueryDto;
import com.stack.model.admin.pojos.AdUser;
import com.stack.model.common.dtos.PageResponseResult;
import com.stack.model.common.dtos.ResponseResult;
import com.stack.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author llz
 * @date 2023/11/14 23:40
 * @description
 */
@Service
@Slf4j
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser>  implements AdUserService {

    @Autowired
    private AdUserMapper adUserMapper;

    /**
     * 登录
     * @param user
     * @return
     */
    @Override
    public ResponseResult login(AdUser user) {
        //1.检查参数
        if(StringUtils.isBlank(user.getName()) || StringUtils.isBlank(user.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码为空");
        }

        //2.查询用户
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, user.getName()));
        if(adUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3.比对密码
        String salt = adUser.getSalt();
        String pswd = user.getPassword();
        pswd = DigestUtils.md5DigestAsHex((pswd + salt).getBytes());
        if(pswd.equals(adUser.getPassword())){
            //4.返回数据  jwt
            Map<String,Object> map  = new HashMap<>();
            map.put("token", AdminJwtUtil.getToken(adUser.getId().longValue()));
            adUser.setSalt("");
            adUser.setPassword("");
            map.put("user",adUser);
            return ResponseResult.okResult(map);

        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
    }

    /**
     * 查看用户列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult getUserList(PageQueryDto dto) {

        //todo 查C端两个平台的用户表

//        //如果不传page pageSize  默认为 1 ,10
//        if (dto.getSize() == null || dto.getSize() == 0) {
//            dto.setSize(10);
//        }
//
//        if (dto.getPage() == null || dto.getPage() == 0) {
//            dto.setPage(1);
//        }
//
//        if (dto.getPage() < 0 || dto.getSize() < 0) {
//            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID); // 参数无效
//        }

        LambdaQueryWrapper<AdUser> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ObjectUtils.isNotEmpty(dto.getStatus()), AdUser::getStatus, dto.getStatus());
        queryWrapper.orderByDesc(AdUser::getCreatedTime);

//        IPage page = new Page(dto.getPage(), dto.getSize());
//        IPage<AdUser> pageList = adUserMapper.selectPage(page, queryWrapper);
//        Integer count = adUserMapper.selectCount(queryWrapper);
//        log.info("数量：{}", pageList.getTotal());
//        log.info("数量：{}", count);

        IPage<AdUser> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<AdUser> pageList = adUserMapper.selectPage(page, queryWrapper);
        log.info("数量：{}", pageList.getTotal());

        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageList.getTotal());
        responseResult.setData(pageList.getRecords());
        return responseResult;
    }

    /**
     * 用户审核通过
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authPass(AdUserDto dto) {
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        AdUser adUser = AdminThreadLocalUtil.getUser();
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        LambdaUpdateWrapper<AdUser> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(AdUser::getId, dto.getId())
                .set(AdUser::getStatus, 9);
        adUserMapper.update(null, updateWrapper);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 用户审核失败
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authFail(AdUserDto dto) {
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        AdUser adUser = AdminThreadLocalUtil.getUser();
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        LambdaUpdateWrapper<AdUser> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(AdUser::getId, dto.getId())
                .set(AdUser::getStatus, 2);
        adUserMapper.update(null, updateWrapper);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
